import { AddLocationParam, EditLocationParam } from "@Tea/model"
import { AppTokenObj } from "../dao/AppToken"
import { ReposBase } from "./RepoBase"
import { renderInsertSql, renderSelectSql, renderUpdateSql } from "../utils/renderSql"

export class LocationRepository extends ReposBase {
  private static inst: LocationRepository

  // 单例
  public static getInstance() {
    if (!LocationRepository.inst) {
      LocationRepository.inst = new LocationRepository()
    }

    return LocationRepository.inst
  }

  locationList(customer: AppTokenObj['userId']) {
    const sql = renderSelectSql({
      database: [
        { name: 'take_overs' }
      ],
      returnFeild: [
        { name: 'take_over_id', aliasName: "takeOverId" },
        "phone",
        "addressee",
        { name: 'vant_val', aliasName: 'vantVal' },
        { name: 'detail_address', aliasName: 'detailAddress' },
        { name: 'is_default', aliasName: "isDefault" },
        "pmd"
      ],
      where: [
        { key: 'customer', sqlVal: customer }
      ]
    })

    return this.query(sql)
  }

  addLocation(params: AddLocationParam, customer: AppTokenObj['userId']) {
    const sql = renderInsertSql({
      database: 'take_overs',
      keyAndVal: [
        { key: 'customer', value: customer },
        { key: 'phone', value: params.phone },
        { key: 'addressee', value: params.addressee, },
        { key: 'vant_val', value: params.vantVal, },
        { key: 'pmd', value: params.pmd },
        { key: 'detail_address', value: params.detailAddress, },
        { key: 'is_default', value: Number(!!params.isDefault) }
      ]
    })

    return this.insert(sql)
  }

  setNotDetault(customer: AppTokenObj['userId']) {
    const sql = `UPDATE take_overs SET is_default = 0 WHERE customer = ${customer}`

    return this.update(sql)
  }

  editLocation(params: EditLocationParam, customer: AppTokenObj['userId']) {
    const sql = renderUpdateSql({
      database: "take_overs",
      keyAndVal: [
        { key: 'customer', value: customer },
        { key: 'phone', value: params.phone },
        { key: 'addressee', value: params.addressee, },
        { key: 'vant_val', value: params.vantVal, },
        { key: 'pmd', value: params.pmd },
        { key: 'detail_address', value: params.detailAddress, },
        { key: 'is_default', value: Number(!!params.isDefault) }
      ],
      where: [
        { key: 'take_over_id', sqlVal: params.takeOverId }
      ]
    })

    return this.update(sql)
  }

  deleteLocation(takeOverId: number, customer: AppTokenObj['userId']) {
    const sql = `DELETE FROM take_overs WHERE take_over_id = ${takeOverId} AND customer = ${customer}`

    return this.delete(sql)
  }
}